package com.tianpengtech.admin.role;
import java.util.Map;

import com.jfinal.plugin.activerecord.Model;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.admin.AbstractAdmin;
import com.tianpengtech.common.model.dictionary.Dictionary;
import com.tianpengtech.common.model.role.Role;
import com.tianpengtech.common.search.LikeCondition;
import com.tianpengtech.common.search.QueryConstructor;
import com.tianpengtech.common.validator.Validator;
import com.tianpengtech.common.validator.rules.numberic.NumbericMustBeGreaterThan;
import com.tianpengtech.common.validator.rules.other.MustBeNull;
import com.tianpengtech.common.validator.rules.string.*;
import org.apache.commons.lang.StringUtils;

public class RoleAdminServiceImpl extends AbstractAdmin{

	@Override
	public void beforeAdd(Model<?> model) throws ValidateException {

		Validator validator = new Validator();
		Role role = RoleDao.ME.readRole(model.getStr(Role.CODE));
		validator.addRule(new MustBeNull(role,"当前角色CODE值已经存在"));
		validator.addRule(new StringLengthBetween(model.getStr(Role.NAME),"角色名称只能输入1-50个字符信息",1,50));
		validator.addRule(new StringMustEngLish(model.getStr(Role.CODE),"角色CODE只能是英文"));
		validator.addRule(new StringLengthBetween(model.getStr(Role.CODE),"角色CODE只能输入1-50个字符信息",1,50));
		validator.addRule(new StringLengthBetween(model.getStr(Role.REMARK),"备注信息只能输入1-50个字符信息",1,50));
		validator.excute();
	}

	@Override
	public void beforeQueryById(Model<?> model, int id) {

	}

	@Override
	public void beforeUpdate(Model<?> model) throws ValidateException {

		Validator validator = new Validator();

		validator.addRule(new StringLengthBetween(model.getStr(Role.NAME),"角色名称只能输入1-50个字符信息",1,50));
		validator.addRule(new StringMustEngLish(model.getStr(Role.CODE),"角色CODE只能是英文"));
		validator.addRule(new StringLengthBetween(model.getStr(Role.CODE),"角色CODE只能输入1-50个字符信息",1,50));
		validator.addRule(new StringLengthBetween(model.getStr(Role.REMARK), "备注信息只能输入1-50个字符信息", 1, 50));
		validator.addRule(new NumbericMustBeGreaterThan(model.getLong(Role.ID),0,"ID必须大于零"));
		validator.excute();
	}

	@Override
	public void beforeDelete(Model<?> model) {

	}

	@Override
	public void builderSQLExpected(Model< ? > model,
			QueryConstructor queryConstruct, Map< String, Object > params) {
		if(StringUtils.isNotEmpty(model.getStr(Role.NAME))){
			queryConstruct.and(new LikeCondition(Role.NAME,"%"+model.getStr(Role.NAME)+"%"));
		}
	}

	@Override
	public String tableName() {
		return Role.dao.tableName();
	}

}